<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\validate\UserAddress;
use think\Hook;

class Address extends Api
{

    /**
     * 地址列表
     *
     * @param string $token token
     */
    public function index()
    {
        $userAddress = new \app\common\model\UserAddress();
        $this->success('', $userAddress->getList($this->auth->id));
    }

    /**
     * 地址详情
     *
     * @param int $id 地址ID
     */
    public function detail($id)
    {
        $userAddress    = new \app\common\model\UserAddress();
        $params         = [
            'where' => [
                'user_id' => $this->auth->id
            ]
        ];

        if ($id) {
            $params['where']['id'] = $id;
        } else {
            $params['where']['is_default'] = 1;
        }

        $this->success('', $userAddress->getDetail($params));
    }

    /**
     * 删除地址
     *
     * @param int $id 地址ID
     */
    public function del($id)
    {
        $userAddress = new \app\common\model\UserAddress();
        if ($userAddress->where(['id' => $id, 'user_id' => $this->auth->id])->delete()) {
            $this->success();
        } else {
            $this->error();
        }
    }

    /**
     * 地址编辑
     *
     * @ApiParams   (name="id", type="integer", required=false, description="地址ID")
     */
    public function save()
    {
        $params                 = input();
        $validate               = new UserAddress();
        $params['user_id']      = $this->auth->id;
        $params['is_default']   = !empty($params['is_default']) && $params['is_default'] == 'true' ? 1 : 0;
        if (!$validate->scene(isset($params['id']) ? 'edit' : 'add')->check($params)) {
            $this->error($validate->getError());
        }

        $userAddress = new \app\common\model\UserAddress();
        if (!$userAddress->setSave($params)) {
            $this->error('地址编辑失败');
        }

        $user = $this->auth->getUser();
        $data = [
            'user'      => &$user,
            'address'   => $params
        ];
        Hook::listen('user_region_handle', $data);

        $this->success('');
    }
}